1079. 活字印刷【中等】
1. 📝 题目描述
你有一套活字字模 tiles,其中每个字模上都刻有一个字母 tiles[i]。返回你可以印出的非空字母序列的数目。
注意:本题中,每个活字字模只能使用一次。
示例 1:
txt
输入:"AAB"
输出:8
解释:可能的序列为 "A", "B", "AA", "AB", "BA", "AAB", "ABA", "BAA"。1
2
3
2
3
示例 2:
txt
输入:"AAABBC"
输出:1881
2
2
示例 3:
txt
输入:"V"
输出:11
2
2
提示:
1 <= tiles.length <= 7tiles由大写英文字母组成
2. 🎯 s.1 - 回溯
js
/**
* @param {string} tiles
* @return {number}
*/
var numTilePossibilities = function (tiles) {
const count = new Array(26).fill(0)
for (const ch of tiles) count[ch.charCodeAt(0) - 65]++
let res = 0
function dfs() {
for (let i = 0; i < 26; i++) {
if (count[i] === 0) continue
res++
count[i]--
dfs()
count[i]++
}
}
dfs()
return res
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
- 时间复杂度:
,其中 是 tiles 的长度 - 空间复杂度:
,递归栈深度
算法思路:
- 统计每个字母的出现次数,用回溯法枚举所有非空序列
- 每一层遍历 26 个字母,若剩余次数 > 0 则选取并递归
- 由于按字母计数而非按位置枚举,自然避免了重复序列